<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;
use app\common\library\SearchLog;

/**
 * 会员接口
 * @ApiWeigh (81)
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     * 
     * @ApiTitle    (获取会员个人信息)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": "用户ID",
          "nickname": "昵称",
          "mobile": "手机号",
          "avatar": "头像",
          "gender": "性别:0=男,1=女,2=未知",
          "realname": "真实姓名",
          "birth_date": "出生日期",
          "birth_time": "出生时间",
          "bio": "个人简介",
          "money": "余额",
          "is_vip": "是否是会员",
          "is_teacher": "是否是老师",
          "order_count": "累计接单量",
          "vip_expire_time": "会员到期时间",
          "createtime": "注册时间",
          "latitude": "纬度",
          "longitude": "经度",
          "location_update_time": "位置更新时间",
          "address": "详细地址",
          "formatted_address": "格式化地址"
        }
      })
     */
    public function index()
    {
        $user = $this->auth->getUser();
        
        // 格式化用户信息
        $data = [
            'id' => $user->id,
            'nickname' => $user->nickname,
            'mobile' => $user->mobile,
            'avatar' => $user->avatar,
            'gender' => $user->gender,
            'realname' => $user->realname,
            'birth_date' => $user->birth_date,
            'birth_time' => $user->birth_time,
            'bio' => $user->bio,
            'money' => $user->money,
            'is_vip' => $user->vip_expire_time > time(),
            'is_teacher' => $user->is_teacher ? true : false,
            'vip_expire_time' => $user->vip_expire_time ? date('Y-m-d H:i:s', $user->vip_expire_time) : null,
            'createtime' => date('Y-m-d H:i:s', $user->createtime),
            'latitude' => $user->latitude,
            'longitude' => $user->longitude,
            'openid' => $user->openid,
            'location_update_time' => $user->location_update_time ? date('Y-m-d H:i:s', $user->location_update_time) : null,
            'address' => $user->address,
            'formatted_address' => $user->formatted_address,
            'city' => $user->city,
            'withdraw_min_price' => config('site.min_price'),
            'withdraw_max_price' => config('site.max_price'),
        ];
        
        // 如果是老师,返回累计接单量
        if($user->is_teacher) {
            $data['order_count'] = \think\Db::name('service_order')
                ->where('teacher_id', $user->id)
                ->where('status', 'in', [1,2]) // 已支付和已完成的订单
                ->count();
        }
        
        $this->success('', $data);
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=false, description="头像地址")
     * @ApiParams (name="nickname", type="string", required=false, description="昵称")
     * @ApiParams (name="realname", type="string", required=false, description="姓名")
     * @ApiParams (name="gender", type="integer", required=false, description="性别:0=男,1=女")
     * @ApiParams (name="birth_date", type="string", required=false, description="出生日期，格式：YYYY-MM-DD")
     * @ApiParams (name="birth_time", type="string", required=false, description="出生时间，格式：HH:mm:ss") 
     * @ApiParams (name="bio", type="string", required=false, description="个人简介")
     * @ApiParams (name="latitude", type="string", required=false, description="纬度")
     * @ApiParams (name="longitude", type="string", required=false, description="经度")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        
        // 获取所有可更新字段
        $fields = [
            'nickname', 'realname', 'gender', 'birth_date', 
            'birth_time', 'bio', 'avatar', 'latitude', 'longitude'
        ];
        
        $data = [];
        foreach($fields as $field) {
            $value = $this->request->post($field);
            if($value !== null && $value !== '') {
                $data[$field] = $value;
            }
        }
        
        // 如果要更新昵称,检查是否存在
        if(isset($data['nickname'])) {
            $exists = \app\common\model\User::where('nickname', $data['nickname'])
                ->where('id', '<>', $this->auth->id)
                ->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
        }
        
        // 验证性别值
        if(isset($data['gender']) && !in_array($data['gender'], [0, 1, 2])) {
            $this->error(__('Invalid gender value'));
        }
        
        // 验证日期格式
        if(isset($data['birth_date']) && !Validate::is($data['birth_date'], 'date')) {
            $this->error(__('Invalid birth date format'));
        }
        
        // 验证时间格式
        if(isset($data['birth_time']) && !preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/', $data['birth_time'])) {
            $this->error(__('Invalid birth time format'));
        }
        
        // 如果有位置信息更新,同时更新更新时间和地址信息
        if(isset($data['latitude']) || isset($data['longitude'])) {
            $data['location_update_time'] = time();
            
            // 获取地址信息
            if(isset($data['latitude']) && isset($data['longitude'])) {
                $addressInfo = \app\common\library\Location::getAddressByLocation($data['latitude'], $data['longitude']);
                if($addressInfo) {
                    $data['address'] = $addressInfo['address'];
                    $data['formatted_address'] = $addressInfo['formatted_address'];
                }
            }
        }

        if(!empty($data)) {
            $user->save($data);
        }
        
        // 返回完整的用户信息
        $result = [
            'id' => $user->id,
            'nickname' => $user->nickname,
            'mobile' => $user->mobile,
            'avatar' => $user->avatar,
            'gender' => $user->gender,
            'realname' => $user->realname,
            'birth_date' => $user->birth_date,
            'birth_time' => $user->birth_time,
            'bio' => $user->bio,
            'money' => $user->money,
            'is_vip' => $user->vip_expire_time > time(),
            'is_teacher' => $user->is_teacher ? true : false,
            'vip_expire_time' => $user->vip_expire_time ? date('Y-m-d H:i:s', $user->vip_expire_time) : null,
            'createtime' => date('Y-m-d H:i:s', $user->createtime),
            'latitude' => $user->latitude,
            'openid' => $user->openid,
            'longitude' => $user->longitude,
            'location_update_time' => $user->location_update_time ? date('Y-m-d H:i:s', $user->location_update_time) : null
        ];
        
        $this->success('', $result);
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 获取VIP信息
     * 
     * @ApiTitle    (获取VIP配置和状态信息)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "success",
     *   "data": {
     *     "config": {
     *       "id": "配置ID",
     *       "price": "会员价格",
     *       "benefits": "会员说明",
     *       "discount": "商品折扣,如:0.8表示8折",
     *       "voucher_times": "服务项目支付代金券次数",
     *       "teachers": [{
     *         "id": "老师ID",
     *         "nickname": "老师昵称",
     *         "username": "老师用户名",
     *         "realname": "老师真实姓名",
     *         "avatar": "头像地址"
     *       }]
     *       "createtime": "创建时间"
     *     },
     *     "is_vip": "是否是会员:true=是,false=否",
     *     "expire_time": "会员到期时间,格式:YYYY-MM-DD HH:mm:ss,未开通时为null"
     *   }
     * })
     */
    public function vip()
    {
        $config = \app\common\model\VipConfig::order('id DESC')->find();
        $user = $this->auth->getUser();
        
        // 获取可用代金券老师列表
        $teacherIds = !empty($config->teacher_ids) ? explode(',', $config->teacher_ids) : [];
        $teachers = [];
        if(!empty($teacherIds)) {
            $teachers = \app\common\model\User::where('id', 'in', $teacherIds)
                ->where('is_teacher', 1)
                ->field(['id', 'nickname', 'avatar','is_teacher','username','realname'])
                ->select();
            // 处理头像
            foreach($teachers as &$teacher) {
                $teacher['avatar'] = cdnurl($teacher['avatar']);
            }
        }
        
        $this->success('', [
            'config' => [
                'id' => $config->id,
                'price' => $config->price,
                'benefits' => $config->benefits,
                'discount' => $config->discount, // 商品折扣
                'voucher_times' => $config->voucher_times, // 服务项目支付代金券次数
                'teachers' => $teachers, // 可用代金券老师列表
                'createtime' => $config->createtime
            ],
            'is_vip' => $user->vip_expire_time > time(),
            'expire_time' => $user->vip_expire_time ? date('Y-m-d H:i:s', $user->vip_expire_time) : null
        ]);
    }

    /**
     * 创建VIP订单
     * 
     * @ApiTitle    (创建新的VIP购买订单)
     * @ApiMethod   (POST)
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "success",
     *   "data": {
     *     "order_id": "订单ID",
     *     "order_no": "订单编号,20位字符串"
     *   }
     * })
     * @ApiSummary  (根据最新的会员配置信息创建订单,订单有效期为1年)
     * @ApiNote     (订单创建后需要调用支付接口完成支付)
     */
    public function createVipOrder()
    {
        $config = \app\common\model\VipConfig::order('id DESC')->find();
        if (!$config) {
            $this->error('会员信息未配置');
        }
        
        $user = $this->auth->getUser();
        
        // 创建订单
        $order = \app\common\model\VipOrder::create([
            'user_id' => $user->id,
            'order_no' => date('YmdHis') . Random::numeric(6),
            'amount' => $config->price,
            'expire_time' => strtotime('+1 year'),
            'status' => \app\common\model\VipOrder::STATUS_UNPAID
        ]);
        
        $this->success('', [
            'order_id' => $order->id,
            'order_no' => $order->order_no
        ]);
    }
    
    /**
     * 支付会员订单
     * 
     * @ApiTitle    (发起VIP订单支付)
     * @ApiMethod   (POST)
     * @ApiParams   (name="order_id", type="integer", required=true, description="订单ID")
     * @ApiParams   (name="pay_type", type="string", required=true, description="支付方式:wechat=微信支付,alipay=支付宝支付")
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "success",
     *   "data": {
     *     "type": "支付方式:wechat=微信支付,alipay=支付宝支付",
     *     "params": "支付参数,APP端用于拉起支付"
     *   }
     * })
     * @ApiSummary  (根据订单ID创建支付交易,返回支付参数)
     * @ApiNote     (支付参数需要在APP端使用对应支付SDK处理)
     */
    public function payVipOrder()
    {
        $order_id = $this->request->post('order_id');
        $pay_type = $this->request->post('pay_type');
        
        // 验证支付方式
        if (!in_array($pay_type, ['wechat', 'alipay'])) {
            $this->error('不支持的支付方式');
        }
        
        $order = \app\common\model\VipOrder::where([
            'id' => $order_id,
            'user_id' => $this->auth->id,
            'status' => \app\common\model\VipOrder::STATUS_UNPAID
        ])->find();
        
        if (!$order) {
            $this->error('订单不存在');
        }
        if($order->amount <= 0){
            $this->error('订单金额错误');
        }
        try {
            // 创建支付
            $notify_url = request()->domain() . '/api/payment/notifyVip/paytype/' . $pay_type;
            $result = \addons\epay\library\Service::submitOrder($order->amount, $order->order_no, 
                $pay_type, '会员购买', $notify_url, '','app');
                
            if (!$result) {
                $this->error('创建支付失败');
            }
            
            $this->success('', [
                'type' => $pay_type,
                'params' => $pay_type == 'wechat' ? json_decode($result, true) : $result
            ]);
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 我的关注列表
     * 
     * @ApiTitle    (获取我关注的老师列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词")
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "老师ID",
            "nickname": "老师昵称",
            "avatar": "头像",
            "bio": "个人简介",
            "gender": "性别",
            "order_count": "累计接单量",
            "latitude": "纬度",
            "longitude": "经度",
            "address": "详细地址",
            "formatted_address": "格式化地址",
            "location_update_time": "位置更新时间"
          }]
        }
      })
     */
    public function followList()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        $keyword = $this->request->get('keyword', '');
        
        $query = Db::name('user_follow')->alias('f')
            ->join('user u', 'u.id = f.teacher_id')
            ->where('f.user_id', $this->auth->id);
            
        // 添加关键词搜索
        if($keyword){
            $query->where(function($query) use ($keyword) {
                $query->where('u.nickname', 'like', "%{$keyword}%")
                    ->whereOr('u.bio', 'like', "%{$keyword}%");
            });
            
            // 记录搜索历史
            SearchLog::record($this->auth->id, $keyword, 'follow');

        }
        
        $list = $query->field([
            'u.id',
            'u.nickname',
            'u.avatar',
            'u.bio',
            'u.gender',
            'u.latitude',
            'u.longitude',
            'u.address',
            'u.formatted_address',
            'u.location_update_time',
            '(SELECT COUNT(*) FROM '.config('database.prefix').'service_order WHERE teacher_id = u.id AND status IN (1,2)) as order_count'
        ])
        ->page($page, $pageSize)
        ->select();
        $total = Db::name('user_follow')->alias('f')
        ->join('user u', 'u.id = f.teacher_id')
        ->where('f.user_id', $this->auth->id)->count();
        // 处理头像完整路径
        foreach($list as &$item) {
            $item['avatar'] = $item['avatar'] ? cdnurl($item['avatar']) : '';
        }
        
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }
    /**
     * 解绑微信
     * 
     * @ApiTitle    (解绑微信账号)
     * @ApiMethod   (POST)
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": "用户ID",
          "nickname": "昵称",
          "mobile": "手机号",
          "avatar": "头像",
          "gender": "性别:0=男,1=女,2=未知",
          "realname": "真实姓名",
          "birth_date": "出生日期",
          "birth_time": "出生时间",
          "bio": "个人简介",
          "money": "余额",
          "is_vip": "是否是会员",
          "is_teacher": "是否是老师",
          "order_count": "累计接单量",
          "vip_expire_time": "会员到期时间",
          "createtime": "注册时间",
          "latitude": "纬度",
          "longitude": "经度",
          "location_update_time": "位置更新时间",
          "address": "详细地址",
          "formatted_address": "格式化地址"
        }
    })
     */
    public function unbindWechat()
    {
        $user = $this->auth->getUser();
        
        if(empty($user->openid)) {
            $this->error('未绑定微信账号');
        }
        
        try {
            $user->openid = '';
            $user->save();
            
            // 返回完整的用户信息
            $data = [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'mobile' => $user->mobile,
                'avatar' => $user->avatar,
                'gender' => $user->gender,
                'realname' => $user->realname,
                'birth_date' => $user->birth_date,
                'birth_time' => $user->birth_time,
                'bio' => $user->bio,
                'money' => $user->money,
                'is_vip' => $user->vip_expire_time > time(),
                'is_teacher' => $user->is_teacher ? true : false,
                'vip_expire_time' => $user->vip_expire_time ? date('Y-m-d H:i:s', $user->vip_expire_time) : null,
                'createtime' => date('Y-m-d H:i:s', $user->createtime),
                'latitude' => $user->latitude,
                'longitude' => $user->longitude,
                'openid' => $user->openid,
                'location_update_time' => $user->location_update_time ? date('Y-m-d H:i:s', $user->location_update_time) : null,
                'address' => $user->address,
                'formatted_address' => $user->formatted_address
            ];
            
            $this->success('解绑成功', $data);
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        }
    }
    /**
     * 绑定微信
     *
     * @ApiTitle    (绑定微信)
     * @ApiSummary  (将微信openid绑定到当前用户)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="微信授权码")
     * @ApiReturn   ({
        "code": 1,
        "msg": "绑定成功",
        "data": {
          "user": {
            "id": 1,
            "openid": "微信openid",
            "nickname": "用户昵称",
            "avatar": "头像地址",
            "createtime": "2024-01-01 00:00:00"
          }
        }
      })
     */
    public function bindWechat()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('参数错误');
        }

        $wx = new \app\common\library\Wechat;
        $userInfo = $wx->getUserInfo($code);

        if (!$userInfo) {
            $this->error('微信授权失败');
        }

        $user = $this->auth->getUser();
        if (!$user) {
            $this->error('用户未登录');
        }

        // 检查openid是否已被其他用户绑定
        if (\app\common\model\User::where('openid', $userInfo['openid'])->where('id', '<>', $user->id)->find()) {
            $this->error('该微信已绑定其他账号');
        }

        // 绑定微信信息
        $user->openid = $userInfo['openid'];
        $user->nickname = $userInfo['nickname'];
        $user->avatar = $userInfo['headimgurl'];
        $user->save();

        $this->success('绑定成功', ['user' => $user]);
    }
}


